package com.ztesoft.report.utils.seqcreate.impl;



import com.ztesoft.report.utils.seqcreate.IdStep;
import com.ztesoft.report.utils.seqcreate.InitIdServ;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
public class InitServImpl implements InitIdServ {

    private final static  String SELECT_SQL = "select MAX_ID,STEP from INIT_ID " +
            "where table_name=? and column_name=? for update";
    private final static String UPDATE_SQL = "update INIT_ID set MAX_ID=? where " +
            "table_name=? and column_name=?";

    private final static String INSERT_SQL = "INSERT INTO INIT_ID (init_id, " +
            "table_name, column_name, data_type, length, ref_code, ref_type, " +
            "max_id, step, refer_table)VALUES (0,?,?,0,?,-1,0,?,?,'')";
    private final static int DEF_STEP = 1;
    private final static int DEF_START = 1;


    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @Override
    public IdStep fetchNew(String tablename, String columnName, int length) {
        long start = 0;
        long end = 0;
        List<Map<String, Object>> list = jdbcTemplate.queryForList(
                SELECT_SQL,new Object[]{tablename, columnName});
        if (list.size() > 0) {
            start = Long.valueOf(list.get(0).get("MAX_ID").toString());
            end = start + Long.valueOf(list.get(0).get("STEP").toString());
        } else {
            start = DEF_START;
            end = start + DEF_STEP;
            jdbcTemplate.update(INSERT_SQL,new Object[]{tablename, columnName,length,start,DEF_START});
            //throw new RException("找不到序列：" + tablename);
        }
        jdbcTemplate.update(UPDATE_SQL,new Object[]{end, tablename, columnName});

        return new IdStep(start, end);
    }
}
